/*
 * @Description  : 请求方法封装
 * @Version      : 1.0
 * @Author       : kangshifu
 * @Date         : 2022-05-30 17:27:09
 * @LastEditors  : kangshifu
 * @LastEditTime : 2022-05-31 23:43:44
 */
import axios, { AxiosRequestConfig} from 'axios'
import { TIMEOUT, HTTPCODE, TOKENOTSTATUS } from '@/request/config'
import { STORAGE_TOKEN } from '@/utils/storage-manage'
import router from '@/router/index'

const BASE_URL: string = import.meta.env.VITE_BASE_URL
declare module 'axios' {
    export interface AxiosRequestConfig {
        noToken?: boolean;
        interceptNot?: boolean,
        header?: object,
        noLoading?: boolean,
        userAgent?: boolean,
        noToast?:boolean
    }
}

let requestConfig = {
    baseURL: BASE_URL,
    timeout: TIMEOUT,
    headers: {
        'Content-Type': 'application/json;charset=UTF-8;',
    },
} as AxiosRequestConfig

const request = axios.create(requestConfig)
request.interceptors.request.use(requestResolve, requestReject)
request.interceptors.response.use(responseResolve, responseReject);


/**
 * @description: 请求拦截
 * @param {any} config
 * @return {*}
 */
async function requestResolve(config: AxiosRequestConfig) {
    config.headers = {
        ...config.headers,
        ...config.header
    }
    if (!config.noLoading) {
        window.Toast.loading({
            duration: 0,
            forbidClick: true,
            message: '加载中',
        });
    }
    console.log(STORAGE_TOKEN.get());
    
    if(config.noToken){       
      config.headers.common['access-token']= STORAGE_TOKEN.get();
    }
   
    
    // 默认请求加上token
  //   if (window.$isApp) {
  //       Object.assign(config.headers,SET_USEINFO.get())
  //   }
    return config
}

/**
 * @description: 请求失败拦截
 * @param {any} error
 * @return {*}
 */
function requestReject(error: any) {
    window.Toast.clear(); // 关闭loading
    return Promise.reject(error)
}


/**
 * @description:响应拦截 
 * @param {response}
 * @return {data}
 */
function responseResolve(response:any) {
    window.Toast.clear(); // 关闭loading
    const { data, config } = response
    // 系统错误
    if (TOKENOTSTATUS.some((v: string) => v == data.state)) {
        console.log('系统错误',config)
        window.Toast(data.msg)
      //   SET_USEINFO.remove()
    }
    // 不拦截任何状态
    if (config.interceptNot) {
        return data
    }
    // interceptNot不为true,默认拦截非200的状态
    if (data.code === 0) {
        // 如果不出现错误，直接向回调函数内输出 data
        return data
    } else {
        // 拦截非200的状态
        let message = data.msg || HTTPCODE.get(data.code) || HTTPCODE.get('default')
        if(!config.noToast){
            window.Toast(message)
        }
        if(data.code=='100018'){
          router.push({path:'/login'})
        }
      //   throw new Error(message)
    }
}

// 响应失败拦截
function responseReject(error: any) {
  console.log(error);
  
    window.Toast.fail({
        message: '请求异常，请稍后再试!',
        duration: 2000
    })
}
export default request